<template>
  <div class="card">
    <h3 class="text-xl font-bold text-text-primary mb-6">我的评论</h3>
    
    <!-- 加载状态 -->
    <div v-if="isLoading" class="flex justify-center py-8">
      <div class="text-text-muted">加载中...</div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="text-center py-8">
      <div class="text-error mb-4">{{ error }}</div>
      <UiButton 
        @click="loadUserComments"
        variant="primary"
      >
        重试
      </UiButton>
    </div>

    <!-- 评论列表 -->
    <div v-else-if="comments.length > 0" class="space-y-4">
      <UserCommentCard 
        v-for="comment in comments" 
        :key="comment.id" 
        :comment="comment"
        :canDelete="isCurrentUser"
        @delete="handleDeleteComment"
      />
    </div>

    <!-- 空状态 -->
    <div v-else class="text-center py-12 text-text-muted">
      还没有发表过评论
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { supabase } from '../../lib/supabase'
import type { Comment } from '../../types/ui'
import UserCommentCard from './UserCommentCard.vue'
import { UiButton } from '../ui'
import { useUserStore } from '../../store/useUserStore'
import { useUserData } from '../../composables/useUserData'

const route = useRoute()
const userStore = useUserStore()
const { getUserComments } = useUserData()
const comments = ref<Comment[]>([])
const isLoading = ref(false)
const error = ref<string | null>(null)

// 检查是否为当前用户
const isCurrentUser = computed(() => {
  const userId = route.params.id as string
  const result = userStore.isCurrentUser(userId)
  console.log('isCurrentUser computed:', {
    currentUserId: userStore.userId,
    pageUserId: userId,
    result: result
  })
  return result
})

const loadUserComments = async () => {
  const userId = route.params.id as string
  if (!userId) return

  isLoading.value = true
  error.value = null
  
  try {
    const userComments = await getUserComments(userId, 20, 0)
    comments.value = userComments
  } catch (err) {
    console.error('Error loading user comments:', err)
    error.value = '加载评论失败'
  } finally {
    isLoading.value = false
  }
}

const handleDeleteComment = async (commentId: number) => {
  console.log('Attempting to delete comment:', commentId)
  console.log('Current user:', userStore.userId)
  console.log('Page user:', route.params.id)
  console.log('Is current user:', isCurrentUser.value)
  
  // 检查权限 - 只有当前用户才能删除自己的评论
  if (!isCurrentUser.value) {
    error.value = '非当前用户，无法删除评论'
    console.warn('Permission denied: not current user')
    return
  }

  try {
    // 首先验证评论是否属于当前用户
    console.log('Fetching comment data for verification...')
    const { data: commentData, error: fetchError } = await supabase
      .from('comments')
      .select('user_id')
      .eq('id', commentId)
      .single()

    if (fetchError) {
      console.error('Error fetching comment:', fetchError)
      throw new Error('评论不存在')
    }

    console.log('Comment data:', commentData)
    console.log('Comment user ID:', commentData.user_id)
    console.log('Current user ID:', userStore.userId)

    // 再次确认权限
    if (commentData.user_id !== userStore.userId) {
      error.value = '您没有权限删除此评论'
      console.warn('Permission denied: comment does not belong to current user')
      return
    }

    console.log('Permission verified, proceeding with deletion...')
    const { error: deleteError } = await supabase
      .from('comments')
      .delete()
      .eq('id', commentId)

    if (deleteError) {
      console.error('Error deleting comment:', deleteError)
      throw deleteError
    }

    console.log('Comment deleted successfully')
    // 从本地列表中移除
    comments.value = comments.value.filter(c => c.id !== commentId)
    
    // 清除错误信息
    error.value = null
  } catch (err) {
    console.error('Error deleting comment:', err)
    error.value = err instanceof Error ? err.message : '删除评论失败'
  }
}

onMounted(() => {
  loadUserComments()
})
</script>